<template>
	<xn-form-container
		:title="formData.id ? '编辑栏区' : '增加栏区'"
		:width="700"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="栏区标志：" name="sign">
				<a-select v-model:value="formData.sign" placeholder="请选择栏区标志" :options="signOptions" @change="handleSignChange" allow-clear />
			</a-form-item>
			<a-form-item label="栏区种类：" name="typeId">
				<a-select v-model:value="formData.typeId" placeholder="请选择栏区种类" :options="typeOptions" allow-clear/>
			</a-form-item>
			<a-form-item label="父栏舍：" name="barnId">
				<barnTreeSelect @update:barnId="handleBarnIdUpdate"/>
			</a-form-item>
			<a-form-item label="栏区状态：" name="state">
				<a-select v-model:value="formData.state" placeholder="请选择栏区状态" :options="stateOptions" />
			</a-form-item>
			<a-form-item label="栏区容量：" name="capacity">
				<a-input v-model:value="formData.capacity" placeholder="请输入栏区容量" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="bizColumnForm">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import bizColumnApi from '@/api/column/bizColumnApi'
	import bizHenhouseApi from "@/api/henhouse/bizHenhouseApi";
	// 抽屉状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)
	const signOptions = ref([])
	const stateOptions = ref([])
	const typeOptions = ref([])
	const data = ref([]);

	// 打开抽屉
	const onOpen = (record) => {
		formData.value.state = '正常';
		visible.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
		}
		signOptions.value = tool.dictList('column_sign')
		stateOptions.value = tool.dictList('barn_status')
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		sign: [required('请输入栏区标志')],
	}

	const handleSignChange = value =>{
		typeOptions.value = value === '肉鸡' ? tool.dictList('broiler_type') : tool.dictList('layer_type');
	}

	const handleBarnIdUpdate = value =>{
		formData.value.barnId = value;
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			bizColumnApi
				.bizColumnSubmitForm(formDataParam, formDataParam.id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
